﻿var is_mob=/(iphone|iPod|iPad|android|ios|windows phone)/i.test(window.navigator.userAgent);
var event_map=function(e){
    if(!is_mob)
        return e;
    var maps={"mousedown":"touchstart","mouseup":"touchend","mousemove":"touchmove","click":"touchend"};
    return maps[e];
}
//$.extend({
//    layer:function(){
//        var that=this;
//        var layers=[];
//        var html='<div id="layer_" >';
//        html+='<div class="pop-bg"></div>';
//        html+='   <div class="main">';
//        html+='<div class="info-edit" id="layer_main">';
//        html+='<h2>{title}<a class="delete" href="javascript:void(0);" data-role="button" data-action="close"></a></h2>';
//        html+='<div style="padding:10px;">{content}</div>';
//        html+='<div align="center" id="layer_buttons" style="position: absolute;text-align: center; bottom: 0;width: 100%;"></div>';
//        html+='</div></div>';
//        function setWidthAndPos(obj,options){
//            //设置宽度与位置
//            var size=options.size || ["auto"];
//            if(size.length==0){
//                size.push("auto");
//                size.push("auto");
//            }else   if(size.length==1){
//                size.push(size[0]);
//            }
//            var layer_man= obj.find("#layer_main").css({width:size[0],height:size[1]});
//            var offset=options.offset || [0,0];
//            if(typeof offset=="array"){
//                if(offset.length==0){
//                    offset=[0,0];
//                }else{
//                    offset.push(0);
//                }
//            }else{
//                offset=[0,0];
//            }
//            var h=size[1]=="auto"?layer_man.height():size[1];
//            var w=size[0]=="auto"?layer_man.height():size[0];
//            layer_man.css({marginTop:-h/2+offset[0],marginLeft:-w/2+offset[1]});
//        }
//        this.open=function(options){
//            var id=new Date().getTime();
//            options= $.extend({type:0,buttons:{ok:"是",cancel:"否"},title:"提示",content:""},options);
//            var obj=$(html.replace("{title}",options.title).replace("{content}",options.content)).attr("id",id).appendTo("body").hide();
//
//            setWidthAndPos(obj,options);
//            switch (options.type){
//                case 0:
//                    //消息框
//                    obj.find("#layer_buttons").append('<a class="quit_blue" href="javascript:void(0);" data-role="button" data-action="ok">'+options.buttons.ok+'</a>');
//                    break;
//                case 1:
//                    //确认框
//                    obj.find("#layer_buttons").append('<a class="quit_blue" style="width:auto;margin-left: 17px;padding: 0 8px;" href="javascript:void(0);" data-role="button" data-action="ok">'+options.buttons.ok+'</a>' +
//                    '<a class="quit_blue" style="width:auto;margin-left: 17px;padding: 0 8px;" href="javascript:void(0);" data-role="button" data-action="cancel">'+options.buttons.cancel+'</a>');
//                    break;
//            }
//            //绑定事件
//
//            obj.on(event_map("click"),"[data-role='button']",function(e){
//                e.preventDefault();
//                //console.log($(this).attr("data-action"));
//                switch($(this).attr("data-action")){
//                    case "ok":
//                        if(options.okCallback){
//                            options.okCallback.call(that);
//                        }
//                        obj.fadeOut(function(){
//                            that.close(id);
//                        });
//                        break;
//                    case "cancel":
//                        if(options.cancelCallback){
//                            options.cancelCallback.call(that);
//                        }
//                        obj.fadeOut(function(){
//                            that.close(id);
//                        });
//                        break;
//                    case "close":
//                        obj.fadeOut(function(){
//                            that.close(id);
//                        });
//                        break;
//                }
//            });
//            //显示层
//            layers.push({id:id,layer:obj});
//            obj.fadeIn();
//            //返回层id；
//            return id;
//        };
//        this.close=function(layer_id){
//            console.log(layer_id);
//            for(var i in layers){
//                if(layers[i].id==layer_id){
//                    layers[i].layer.remove();
//                }
//            }
//        }
//        this.alert=function(msg){
//            //消息框
//            this.open({
//                type:0,
//                content:msg,
//                buttons:{ok:"确认"}
//            })
//        }
//        this.confirm=function(msg,options){
//            //确认
//            options= $.extend({buttons:{ok:"确认",cancel:"取消"},okCallback:function(){},cancelCallBack:function(){}},options);
//            //确认框
//            this.open($.extend(options,{
//                type:1,
//                content:msg
//            }))
//        }
//    }
//});
////实例化一个layer
//window.layer=new $.layer();
$.fn.extend({
    scrollpic:function(options){
        options= $.extend({scale:300/600,effect:"scroll",time:1000*3},options);
        function layout(){
            //对视窗进行布局
        }
        var that=this;
        var obj=$(this);
        var obj_ul=obj.find("ul");
        var wid =obj.width();
        var hei = wid*options.scale;
        //通过图片宽高比例算出高度，图片宽高比例有变在此改
        var num = obj_ul.find("li").length;
        var ulwidth = wid*(num+1);
        //初始化各元素宽高
        obj.css({"height":hei});
        obj_ul.css({"width":ulwidth,"height":hei});
        obj_ul.children("li").css("width",wid);
        $(window).resize(function(){
            wid = obj.width();
            hei =wid*options.scale;
            ulwidth = wid*(num+1);
            obj.css({"height":hei});
            obj_ul.css({"width":ulwidth,"height":hei,"left":pic==num?0:-pic*wid});
            obj.find("ul li").css("width",wid);
        });  //支持缩放，屏幕缩放时重新获取宽高


        var pic = 0;
        var auto,mybtn,_left,s_left,m_left,e_left,s_top,m_top,e_top;
        var btn = "<span class='action'>&bull;</span>";
        for(var i=1;i<num;i++){
            btn += "<span>&bull;</span>";
        }
        $(".button").append(btn);
        mybtn = $(".button span");

        function play(pic){
            if(pic==num){
                obj_ul.append(obj_ul.find("li:first").clone());
                _left = -pic*wid;
                obj_ul.stop(true,false).animate({"left":_left},1000,function(){
                    obj_ul.css("left",0);
                    obj_ul.find("li:last").remove();
                    _left = 0;
                });
                mybtn.eq(0).addClass("action").siblings().removeClass("action");
            }
            else{
                _left = -pic*wid;
                obj_ul.stop(true,false).animate({"left":_left},1000);
                mybtn.eq(pic).addClass("action").siblings().removeClass("action");
                var num2 = obj_ul.find("li").length;
                if(num2>num){obj_ul.find("li:last").remove();}
            }
        }//播放函数

        function start(){
            clearInterval(auto);
            auto = setInterval(function(){
                if(pic<num){pic++;}
                else{pic=1;}
                play(pic);
            },options.time);
        }//建立函数自动播

        $(".box").hover(function(){
            clearInterval(auto);
        },function(){
            start();
        }).trigger("mouseout");   //兼容PC

        mybtn.click(function(){
            var index = $(this).index();
            pic = index;
            play(pic);
        });                    //点击圆点切换图片
        var mouse_down=false;
        obj_ul.on(event_map("mousedown"),function(e){
            //e.preventDefault();
            mouse_down=true;
            if(event.touches)
                e=event.touches[0];
            s_left =e.clientX;
            s_top = e.clientY;
            clearInterval(auto);             //触屏时清除自动播放
        });
        obj_ul.on(event_map("mousemove"),function(e){
            if(mouse_down){
                //e.preventDefault();
                clearInterval(auto);             //触屏时清除自动播放
                if(event.touches)
                    e=event.touches[0];
                m_left = e.clientX;
                m_top = e.clientY;
                e_left = m_left-s_left;
                e_top = m_top-s_top;
                if(Math.abs(e_top)>Math.abs(e_left)){return;}
                else{event.preventDefault();$(this).css("left",_left+e_left);}
            }
        });
        obj_ul.on(event_map("mouseup"),function(e){
            //e.preventDefault();
            if(mouse_down){
                mouse_down=false;
                if(e_left<-60){
                    if(pic<num){pic++;}
                    else{pic=1;}
                    play(pic);
                }
                else if(e_left>60){
                    if(pic>0&&pic<num){pic--;}
                    else{pic=0;}
                    play(pic);
                }
                else{$(this).stop(true,false).animate({"left":_left},300);}
                start();           //手指离开屏幕时启动自动播放
            }
        });
    },
    banner:function(options){
        //banner动画效果
        var op= $.extend({scale:390/720,effect:"scroll",time:1000*5},options);
        var viewBox=$(this);
        var box=viewBox.find("ul");
        var width=viewBox.width();
        var height=0;
        var pic_num=box.find("li").length;
        var init=true;
        function layout(){
            //对视窗进行布局
            width=viewBox.width();
            height=width*op.scale;
            viewBox.height(height);
            switch (op.effect){
                case "scroll":
                    box.width(width*(pic_num+1)).height(height).children().width(width);
                    break;
                case "fade":
                    box.width(width).height(height).children().width(width).css({position: "absolute",top: 0});
                    if(init){
                        box.children(":not(:first)").hide();
                        init=false;
                    }
                    break;
            }
        }
        var index=0;
        function play(){
            switch (op.effect){
                case "scroll":

                    break;
                case "fade":
                  var pre=index++
                  if(index==pic_num)
                        index=0;
                  box.children().eq(pre).fadeOut(600).end().eq(index).fadeIn(1200);
                    break;
            }
        }
        var handle=null;
        function autoPlay(){
            handle=setInterval(play,op.time);
        }
        //绑定事件
        viewBox.on("mouseover",function(){
            clearInterval(handle);
        }).on("mouseout",function(){
            autoPlay();
        }).on("touchstart",function(){
            clearInterval(handle);
        }).on("touchend",function(){
            autoPlay();
        });
        $(window).resize(function(){
           layout();
        });
        layout();
        autoPlay();
    },
    num_select:function(changed_callback){
        //数字选择器
        var sender=$(this);
        var slider=null;//数字滑动器
        var that=this;
        //var orinum=curNum=1;
        var sub_btn=sender.find("[data-role='button'][data-action='subnum']");
        var add_btn=sender.find("[data-role='button'][data-action='addnum']");
        var num_txt=sender.find("[data-role='textbox']");
        var  orinum=curNum=Number(num_txt.val() || 0);
        var slider_h=sender.height()*5;
        var count=5;
        function num_changed(){
            if(orinum!=curNum){
                num_txt.val(curNum);
                changed_callback.call(that,orinum,curNum);
            }
        }
        function setpos(){
            slider.css({top:sender.offset().top-slider_h/2+sender.height()/2,left:sender.offset().left})
                .children("ul").css({marginTop:-(sender.height())*(count*2+1)/2})
                .children("li:eq("+(Math.ceil((count*2+1)/2))+")").css({borderTop:"1px solid #ddd",borderBottom:"1px solid #ddd"})
                .siblings().css({borderTop:"",borderBottom:""});;
        }
        //添加事件
        sub_btn.on(event_map("click"),function(e){
            e.preventDefault();
            orinum=curNum--;
            //if(curNum<1)
            //    curNum=1;
            num_changed();
        });
        add_btn.on(event_map("click"),function(e){
            e.preventDefault();
            orinum=curNum++;
            num_changed();
        });
        //长按，则显示滑动控件
        var enabled=false;
        var mousedown=false;
        var timer=null;
        slider="<div style='position:absolute;display: none; background-color:#fff;text-align: center ;overflow: hidden;'>" +
        "<ul style='position: relative;top: 50%;border-left:1px solid #ddd;border-right:1px solid #ddd;'>";
        for(var i=count;i>=-count;i--){
            slider+='<li data-value="'+i+'" style="'+(i==0?"border-top:1px solid #ddd;border-bottom:1px solid #ddd;":"")+'">'+(i>0?'+':'')+i+'</li>';
        }
        slider+="</ul></div>";
        slider=$(slider);
        slider.css({width:sender.width(),height:slider_h,opacity:0.5})
            .children("ul").css({opacity:0.7})
            .children("li").css({height:sender.height(),lineHeight:sender.height()+"px"})
            .end().end().appendTo("body");
        setpos();
        var b_y=0;//用来记录每次鼠标移动的开始位置
        var e_y=0;//用来记录最后移动的位置；
        var slider_m_t=0;
        sender.on(event_map("mousedown"),function(e){
            event.preventDefault();
            if(event.touches)
                e=event.touches[0];
            //开始检测时间,如果时间超过1秒，则显示滑动杆
            mousedown=true;
            timer=setTimeout(function(){
                if( !enabled && mousedown){
                    enabled=true;
                    //记录开始滑动位置
                    b_y= e.pageY;
                    setpos();
                    slider_m_t=Number(slider.children("ul").css("marginTop").replace("px",""));
                    orinum=curNum;
                    //重置一下位置
                    slider.show();
                    $(window).on(event_map("mousemove"),function(e){
                        event.preventDefault();
                        if(mousedown && enabled){
                            //开始计算数值
                            if(event.touches)
                                e=event.touches[0];
                            var offset_y=e.pageY-b_y;
                            var offset=Math.ceil((e.pageY-b_y)/sender.height());
                            sender.find("input[data-role='textbox']").val(orinum+offset);
                            //设置当前单元
                            slider.children("ul").css({marginTop: slider_m_t+offset_y})
                                .children("li:eq("+(Math.ceil((count*2+1)/2)-offset-1)+")")
                                .css({borderTop:"1px solid #ddd",borderBottom:"1px solid #ddd"})
                                .siblings().css({borderTop:"",borderBottom:""});
                            e_y= e.pageY;
                        }
                    });
                }
                clearTimeout(timer);
            },1000);
        });
        //窗口大小改变
        $(window).on("resize",function(){
            setpos();
        }).on(event_map("mouseup"),function(e){
            //event.preventDefault();
            clearTimeout(timer);
            if(enabled){
                slider.hide();
                var offset=Math.ceil((e_y-b_y)/sender.height());
                curNum+=offset;
                num_changed();
                enabled=false;
                $(window).unbind(event_map("mousemove"));
            }
            mousedown=false;
            //$(window).unbind(event_map("mouseup"));
        });
    },
    buy_card:function(status_change_callback){
        //定义购物车点击事件
        var targets=$(this);
        targets.on(event_map("click"),function(e){
            e.preventDefault();
            var sender=$(this);
            var status=sender.attr("data-status") || 0;//选择未选中

            if (status == 1) {
                status = 0;
                //sender.removeClass("shop-cur").attr("data-status", status)
                sender.removeClass("shop-cur").attr("data-status", status);
            } else {
                status = 1;
                sender.addClass("shop-cur").attr("data-status", status);
                    //.siblings().removeClass("shop-cur").attr("data-status", 0);
            }
            status_change_callback.call(this,status);
        });
    },
    text_counter:function(options){
        //文本计数器
        options= $.extend({maxLength:500},options);
        function counter(){
            var sender=$(this);
            //统计字符数时，要去掉其中的回车符
            var l=sender.val().replace(/[\n\r]/g,"").length;
            if(l>=options.maxLength){
                l=options.maxLength;
                sender.val(sender.val().substring(0,l));
            }
            if(options.msgTarget){
                $(options.msgTarget).html(l+"/"+options.maxLength+"字");
            }
        }
        $(this).on("input",function(){
            var that=$(this);
            counter.call(this);
        });
        $(options.msgTarget).html("0/"+options.maxLength+"字");
    },
    file_selecter:function(options){
        options= $.extend({fileid:"uploadfile",accept:"*"},options);
        //文件选择器
        $(this).on(event_map("click"),function(e){
            e.preventDefault();
            var sender=$(this);
            var file=sender.attr("data-file") || options.fileid;
            //判断当前是否自己绑定了一个文件控件
            if($("#"+file).size()!=1){
                //添加一个文件隐藏域

                $('<input type="file" id="'+file+'" name="'+file+'" accept="'+options.accept+'"  style="display:none;">').insertAfter(this);
            }
            $("#"+file).click();
        });
    },
    left_menu:function(menus){
        var that=this;
        var menu=null;
        var sub_menu=null;
        var html='<div class="hk-phoneMenu" style="left:-240px;">';
        html+='<ul>';
        $.each(menus,function(i){
            menu=this;
            //是否有子菜单
            var has_sub=menu.sub_items && $.isArray(menu.sub_items) && menu.sub_items.length>0;
            if(has_sub){
                html+='<li data-role="menu" data-menu="#menu'+i+'"  class="nav-borb">'+menu.title;
                html+='<span class="hk-phoneArr1 up"></span>'
                html+='</li>';
                html+='<div id="menu'+i+'" class="hk-phoneNavAb " style="display:none;background: #333333;">';
                for(var i in menu.sub_items){
                    var sub_menu=menu.sub_items[i];
                    html+='<li class="font15"><a href="'+sub_menu.href+'">'+sub_menu.title+'</a></li>';
                };
                html+='</div>';
            }else{
                html+='<li class="nav-borb"><a href="'+menu.href+'">'+menu.title+'</a></li>';
            }
        });
        html+='</ul>';
        html+='</div>';
        var obj_menu =$(html);
        var offset_left=240;
        var showed=false;
        var show_menu=function(){
            obj_menu.animate({left:0},600);
            $(that).attr("data-status",0);
            $(".main:first").animate({left:offset_left},600);
            showed=true;
        };
        var hide_menu=function(){
            obj_menu.animate({left:-offset_left},600);
            $(that).attr("data-status",1);
            $(".main:first").animate({left:0},600);
            showed=false;
        }

        obj_menu.insertBefore(".main:first").find("[data-role='menu']").on(event_map("click"),function(e){
            e.preventDefault();
            var sender=$(this);
            var hided=Number(sender.attr("data-status") || "1");
            if(hided==1){
                sender.next(sender.attr("data-menu")).removeClass("hide").slideDown(function(){
                    //$(this).addClass("show")
                    sender.attr("data-status",0).children("span").addClass("down").removeClass("up");
                });
                var temp_menu=sender.siblings("li[data-role='menu']").attr("data-status",1).children("span").addClass("up").removeClass("down").end();
                temp_menu.next(temp_menu.attr("data-menu")).removeClass("show").slideUp();
            }else{
                sender.next(sender.attr("data-menu")).removeClass("show").slideUp(function(){
                    //$(this).addClass("hide");
                    sender.attr("data-status",1).children("span").addClass("up").removeClass("down");
                });
            }

        }).end();
        //加点击事件
        $(that).on(event_map("click"),function(){
            var sender=$(this);
            var hided=Number(sender.attr("data-status") || "1");
            if(hided){
                show_menu();
            }else{
                hide_menu();
            }

        });
        //增加滑动显示与关闭
        var b_p=0;//开始位置
        var e_p=0;//结束位置
        $(window).on(event_map("mousedown"),function(e){
            //e.preventDefault();
            //e.stopPropagation();
            if(event.touches)
                e= event.touches[0];
            b_p=e_p= e.clientX;
        }).on(event_map("mousemove"),function(e){
            if(showed){
                e.preventDefault();
            }
            //e.stopPropagation();
            if(event.touches)
                e= event.touches[0];
            e_p= e.clientX;
        }).on(event_map("mouseup"),function(e){
            //e.preventDefault();
            var r=e_p-b_p;
            if(Math.abs(r)>=100){
                //滑动了100像素，则显示或关闭
                if(r>0){
                    //显示
                    show_menu();
                }else if(r<0){
                    //关闭
                    hide_menu();
                }
            }
        });
    }
})
